import preferences from '@ohos.data.preferences';
import json from '@ohos.util.json';
import { JSON } from '@kit.ArkTS';
class PreferencesUtil{
  // pref:preferences.Preferences
  preMap:Map<string,preferences.Preferences>= new Map()
  async loadPreference(context,name:string){

    try {
      let pref = await preferences.getPreferences(context, name)
      this.preMap.set(name, pref)
      console.log('testTag',`加载Preference[${name}]成功`)
    } catch (e) {
      console.log('testTag',`加载Preference[${name}]失败`,JSON.stringify(e))
    }
    }
  async putPreferenceValue(name:string,key:string,value:preferences.ValueType){
    if (!this.preMap.has(name)) {
      console.log('testTag',`加载Preference[${name}]尚未初始化`)
        return
    }
    try {
      let pref = this.preMap.get(name)
      //写入数据
      await pref.put(key, value)

      await pref?.flush()
      console.log('testTag', `保存Preference[${name}.${key}=${value}]成功`)
    } catch (e) {
      console.log('testTag', `保存Preference[${name}.${key}=${value}]失败`,JSON.stringify(e))
    }
  }
  async getPreferenceValue(name:string,key:string,defaultValue:preferences.ValueType){
    if (!this.preMap.has(name)) {
      console.log('testTag',`加载Preference[${name}]尚未初始化`)
      return
    }
    try {
      let pref = this.preMap.get(name)
      //读数据
      let value=await pref?.get(key, defaultValue)
      console.log('testTag', `读取Preference[${name}.${key}=${value}]成功`)
      return value
    } catch (e) {
      console.log('testTag', `读取Preference[${name}.${key}]失败`,JSON.stringify(e))
    }
  }
}
const preferencesUtil = new PreferencesUtil()

export default preferencesUtil as PreferencesUtil